package cn.nyist.zyj.controller;


import cn.nyist.zyj.entity.User;
import cn.nyist.zyj.service.UserService;
import cn.nyist.zyj.utils.JWTUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String, Object> login(User user){
        log.info("用户名：[{}]", user.getUsername());
        log.info("用户密码：[{}]", user.getPassword());
        HashMap<String, Object> map = new HashMap<>();
        try {
            User userDB = userService.login(user);

            HashMap<String, String> payload = new HashMap<>();
            payload.put("id", userDB.getId());
            payload.put("username", userDB.getUsername());

            // 生成jwt令牌
            String token = JWTUtils.getToken(payload);

            //把token返回让客户端保存
            map.put("token", token);

            map.put("state", true);
            map.put("msg", "认证成功");
        }catch (Exception e){
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }


    @PostMapping("/test/test")
    public Map<String, Object> test(String token) {
        Map<String, Object> map = new HashMap<>();
        try {
            JWTUtils.verify(token);
            map.put("msg", "验证通过~~~");
            map.put("state", true);
        } catch (TokenExpiredException e) {
            map.put("state", false);
            map.put("msg", "Token已经过期!!!");
        } catch (SignatureVerificationException e){
            map.put("state", false);
            map.put("msg", "签名错误!!!");
        } catch (AlgorithmMismatchException e){
            map.put("state", false);
            map.put("msg", "加密算法不匹配!!!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "无效token~~");
        }
        return map;
    }



}
